package leetcodev1.数组;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class LeetCode46 {

    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();

        List<Integer> output = new ArrayList<Integer>();
        for (int num : nums) {
            output.add(num);
        }

        int n = nums.length;
        backtrack(n, output, res, 0);
        return res;
    }

    //临时中间结果output
    //感觉更简洁和巧妙
    public void backtrack(int n, List<Integer> output, List<List<Integer>> res, int first) {
        // 所有数都填完了
        if (first == n) {
            res.add(new ArrayList<Integer>(output));
        }
        //利用swap代替是否选过
        for (int i = first; i < n; i++) {
            // 动态维护数组
            Collections.swap(output, first, i);
            // 继续递归填下一个数
            backtrack(n, output, res, first + 1);
            // 撤销操作
            Collections.swap(output, first, i);
        }
    }

    private List<List<Integer>> ret = new ArrayList<>();

    //使用回溯法 选|不选
    public List<List<Integer>> permute1(int[] nums) {
        dfs(nums, new ArrayList<>());
        return ret;
    }

    private void dfs(int[] nums, List<Integer> router) {
        if (router.size() == nums.length) {
            ret.add(new ArrayList<>(router));
            return;
        }

        for (int num : nums) {
            //选过的数就不选了
            //判断是否选过该数效率太低
            if (router.contains(num)) {
                continue;
            }

            router.add(num);
            dfs(nums, router);
            router.remove(router.size() - 1);
        }
    }
}
